package com.power.using.mybomb.base;

import android.content.Context;
import android.text.TextUtils;
import android.widget.ImageView;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.power.using.mybomb.util.DisplayConfig;

/**
 * Created by 聪明一只哈 on 2020/3/18.
 * Time: 2020/3/18  14:48
 */
public class UniversalImageLoader implements ILoader {

    public UniversalImageLoader() {
    }

    @Override
    public void loadAvator(ImageView iv, String url, int defaultRes) {

        if(!TextUtils.isEmpty(url)){
            display(iv,url,true,defaultRes,null);
        }else{
            iv.setImageResource(defaultRes);
        }

    }



    @Override
    public void load(ImageView iv, String url, int defaultRes, ImageLoadingListener listener) {

        if(!TextUtils.isEmpty(url)){
            display(iv,url.trim(),false,defaultRes,listener);
        }else{
            iv.setImageResource(defaultRes);
        }
    }


    /**
     * 展示图片
     * @param iv
     * @param url
     * @param isCircle
     * @param defaultRes
     * @param listener
     */
    private void display(ImageView iv, String url, boolean isCircle, int defaultRes, ImageLoadingListener listener) {
        if(!url.equals(iv.getTag())){
            iv.setTag(url);
            ImageViewAware imageViewAware = new ImageViewAware(iv, false);
            ImageLoader.getInstance().displayImage(url,imageViewAware, DisplayConfig.getDefaultOptions(isCircle,defaultRes),listener);
        }
    }

    /**
     * 初始化Imageloader
     * @param context
     */
    public static void initImageLoader(Context context){

        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
        config.threadPoolSize(3);
        config.memoryCache(new WeakMemoryCache());
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
//        config.writeDebugLogs(); // Remove for release app
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());
    }
}
